package com.hisan.freeride.home.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;

import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.event.FirstEvent;
import com.hisan.freeride.common.state.EmptyState;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.databinding.MyaddressBinding;
import com.hisan.freeride.home.adapter.SiteAdapter;
import com.hisan.freeride.home.model.MyAddress;
import com.lzy.okgo.OkGo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;



/**
 *地址页面
 * Created by admin on 2017/5/6.
 */

public class AddressActivity extends BaseActivity<MyaddressBinding>{
    private SiteAdapter siteAdapter;
    private Intent intent;
    private List<MyAddress>addressList;
    private long id;

    @Override
    protected int getLayoutId() {
        return R.layout.myaddress;
    }

    @Override
    protected void initView() {
        // 1.注册事件订阅者
        EventBus.getDefault().register(this);
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.setStateModel(mStateModel);
        siteAdapter=new SiteAdapter(this);
        mBinding.rvList.setAdapter(siteAdapter);
    }

    @Override
    protected void initEvent() {
        mBinding.rvList.setOnItemClickListener((parent, view, position, id) -> {
            if (intent==null){
                intent=new Intent();
            }
            if (!CollectionUtils.isNullOrEmpty(addressList)){
                MyAddress address=addressList.get(position);
                intent.putExtra("id",address.getId());
                setResult(99,intent);
                finishActivity(true);
            }
        });
        mBinding.add.setOnClickListener(v -> startActivityForResult(BuyAddressActivity.class,99,null,true));
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<List<MyAddress>>get(AppConfig.Myaddress)
                .tag(this)
                .execute(new DialogCallback<List<MyAddress>>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<MyAddress>> response) {
                        super.onSuccess(response);
                        addressList=new ArrayList<>();
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            mStateModel.setEmptyState(EmptyState.NORMAL);
                            addressList=response.body();
                            siteAdapter.setData(response.body());
                        }else {
                            mStateModel.setEmptyState(EmptyState.EMPTY);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<List<MyAddress>> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }




    // 3.接收方处理消息（处理数据）-- 主线程中执行
    @Subscribe(threadMode = ThreadMode.MAIN)
    //通知更新方法
    public void onDataSynEvent(FirstEvent event) {
         id=event.getId();
        int position=event.getPosition();
        int stauts=event.getStauts();
        if (stauts==1){
            OkGo.put(AppConfig.DefaultAddress)
                    .tag(this)
                    .params("id",id)
                    .execute(new DialogCallback<Object>(this){
                        @Override
                        public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                            super.onSuccess(response);
                            if (!CollectionUtils.isNullOrEmpty(response.body())){
                                if (isOk(response)){
                                    showToast("设置成功");
                                    MyHandlerUtil.getHandler().postDelayed(() -> loadData(true),200);
                                }else {
                                    showError(response);
                                }
                            }
                        }
                        @Override
                        public void onError(com.lzy.okgo.model.Response<Object> response) {
                            super.onError(response);
                            showError(response);
                        }
                    });
        }else if (stauts==2){
            getmDialog("是否确认删除此地址？","取消","确定");
        }else if(stauts==3){
            if (!CollectionUtils.isNullOrEmpty(addressList)){
                MyAddress address=addressList.get(position);
                Bundle bundle=new Bundle();
                bundle.putInt("id",(int)address.getId());
                bundle.putString("name",address.getName());
                bundle.putString("mobile",address.getMobile());
                bundle.putString("province",address.getProvince());
                bundle.putString("city",address.getCity());
                bundle.putString("area",address.getArea());
                bundle.putString("street",address.getStreet());
                bundle.putString("code",address.getPostcode());
                bundle.putInt("default",address.getIs_default());
                startActivityForResult(BuyAddressActivity.class,99,bundle,true);
            }
        }
    }

    @Override
    public void onOk() {
        super.onOk();
        OkGo.delete(AppConfig.DelAddress)
                .tag(this)
                .params("id",id)
                .execute(new DialogCallback<Object>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                showToast("删除成功");
                                MyHandlerUtil.getHandler().postDelayed(() -> loadData(true),200);
                            }else {
                                showError(response);
                            }
                        }
                    }
                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    @Override
    public void onCancel() {
        super.onCancel();
        if (mDialog.isShowing())mDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册EventBus
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==99){
            loadData(true);
        }
    }
}
